/*获取商品类型下拉*/
getSpecialTypeId();
function getSpecialTypeId() {
    $.ajax({
        url: root.goodsInter.goods_getSpecialSkuTypes,
        cache: false, //禁用缓存
        type: "POST",
        data: {
            isZeroStock: 0
        },
        success: function (data) {
            if (data.errorCode == 0) {
                var specialSkuTypesHtml = '<option value="" selected>不限</option>';
                for (var i = 0; i < data.data.length; i++) {
                    specialSkuTypesHtml += '<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>';
                }
                $(".specialTypeId").html(specialSkuTypesHtml);
            }
        }
    });
}

var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function goodsList(data) {
    if (dataSource.length > 0) {
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if (data.data.list != null) {
        $.each(data.data.list, function (i, field) {
            var rowData = new Array();
            rowData.push(field.skuId);
            rowData.push(field.skuCode);
            rowData.push(field.specialTypeName);
            rowData.push(field.areaName);
            rowData.push(field.actualStock);
            rowData.push(statusFilter(field.salesStatus));
            rowData.push(field.spuId);
            dataSource.push(rowData);
        });
    }
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [{
                "visible": true,
                "targets": 0
            },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<span><td><input class="spuId" type="checkbox" name="spuId" spuid="'+row[6]+'" skuid = "'+row[0]+'" value=""></td></span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<span specialtypeid=1>'+row[2]+'</span>';
                        return val;
                    },
                    "targets": 2
                }
            ],
            "fnInitComplete": function (oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function () {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });
            }
        });
        power();
    };
}
function statusFilter(status) {
    switch (status) {
        case 0:
            return "未上架";
            break;
        case 1:
            return "已上架";
            break;
        case 2:
            return "已下架";
            break;
    }
}
function reloadSpuTable() {
    $.ajax({
        contentType: 'application/json',
        url: root.goodsInter.goods_getSpecialSkuList,
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify({
            pageSize: 50,
            nowPage: 1,
            model: {
                areaId: $("#areaId").html(),
                specialTypeId: $(".specialTypeId").val(),
                salesStatus: $("#saleStatus").val(),
                actualStockZero: $(".actualStockZero").val(),
                skuCode: $(".skuCode").val()
            } //传入组装的参数
        }),
        success: function (data) {
            goodsList(data);
            $("#spu_all").attr("checked", false);
            totalPage = data.data.totalPage;
            $('.M-box3').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    console.log(api.getCurrent());

                    $.ajax({
                        contentType: 'application/json',
                        url: root.goodsInter.goods_getSpecialSkuList,
                        // url: "http://localhost:8080/product/product/spuList",
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            pageSize: 50,
                            nowPage: api.getCurrent(),
                            model: {
                                areaId: $("#areaId").html(),
                                specialTypeId: $(".specialTypeId option:selected").val(),
                                salesStatus: $("#saleStatus option:selected").val(),
                                actualStockZero: $(".actualStockZero option:selected").val(),
                                skuCode: $(".skuCode").val()
                            } //传入组装的参数
                        }),
                        success: function (data) {
                            console.log(data)
                            goodsList(data);
                            $("#spu_all").attr("checked", false);
                        }
                    });
                }
            });
        }
    });
}

//获取用户信息
var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
var JsonObject = JSON.parse(localStorageParameters);

var allIds = ""; //批量上下架的id
function stopProp() {
    /*批量上架全选框阻止冒泡*/
    var timer = setTimeout(function () {
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num, $("#productManage"));
        clearTimeout(timer);
    }, 200);

    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}

//批量上架
function goods_up(obj) {
    layer.confirm('确定要上架吗？', function (index) {
        allIds = document.getElementsByClassName('spuId');
        var ids = [];
        for (var i = 0; i < allIds.length; i++) {
            if (allIds[i].checked == true) {
                ids.push(allIds[i]);
            }
        }
        console.log(ids)
        var idArr = [];
        for (var i = 0; i < ids.length; i++) {
            idArr.push({"skuId":$(ids[i]).attr("skuid"), "spuId":$(ids[i]).attr("spuid")});
        }
        var spu_data = {
            data: idArr,
            status: 1,
            saleAreaId: $("#areaId").html(),
            lastModifiedBy: JsonObject.user.user_ID
        }
        $.ajax({
            contentType: 'application/json',
            url: root.goodsInter.setSpecialSKUSaleStatus,
            cache: false, //禁用缓存
            type: "POST",
            data: JSON.stringify(spu_data),
            success: function (data) {
                if (data.errorCode == 0) {
                    if(data.saleFail==0){
                        layer.msg("商品上架成功", {
                            icon: 6,
                            time: 1000
                        }, function () {
                            reloadSpuTable();
                        });
                    }else {
                        layer.open({
                            title: '提示',
                            content: data.saleOn+"个商品上架成功,"+data.saleFail+"个商品上架失败。"
                            +(data.failPullUpSkuCodeList==""?"":data.failPullUpSkuCodeList+"为淘汰商品、积压促销商品、分货销售商品且实际库存为0，不能上架！"),
                            yes: function(index, layero){
                                //do something
                                reloadSpuTable();
                                layer.close(index); //如果设定了yes回调，需进行手工关闭
                            }
                        });

                    }
                } else {
                    layer.msg("商品上架失败", {
                        icon: 6,
                        time: 1000
                    }, function () {
                        reloadSpuTable();
                    });
                }
            }
        });
    });
}

//批量下架
function goods_down(obj) {
    layer.confirm('确定要下架吗？', function (index) {
        allIds = document.getElementsByClassName('spuId');
        var ids = [];
        for (var i = 0; i < allIds.length; i++) {
            console.log(allIds[i].checked)
            if (allIds[i].checked == true) {
                ids.push(allIds[i]);
            }
        }
        var idArr = [];
        for (var i = 0; i < ids.length; i++) {
            idArr.push({"skuId":$(ids[i]).attr("skuid"), "spuId":$(ids[i]).attr("spuid")});
        }
        var spu_data = {
            data: idArr,
            status: 2,
            saleAreaId: $("#areaId").html(),
            lastModifiedBy: JsonObject.user.user_ID
        }
        $.ajax({
            contentType: 'application/json',
            url: root.goodsInter.setSpecialSKUSaleStatus,
            cache: false, //禁用缓存
            type: "POST",
            data: JSON.stringify(spu_data),
            success: function (data) {
                if (data.errorCode == 0) {
                    if(data.failPullUpSkuCodeList==""){
                        layer.msg("商品下架成功", {
                            icon: 6,
                            time: 1000
                        }, function () {
                            reloadSpuTable();
                        });
                    }else {
                        layer.open({
                            title: '提示',
                            content: data.saleOn+"个商品下架成功,"+data.saleFail+"个商品下架失败",
                            yes: function(index, layero){
                                //do something
                                reloadSpuTable();
                                layer.close(index); //如果设定了yes回调，需进行手工关闭
                            }
                        });
                        /*layer.msg(data.failPullUpSkuCodeList+"为淘汰商品、积压促销商品、分货销售商品且实际库存为0，不能上架！其他正常商品上架成功", {
                            icon: 6,
                            time: 2000
                        }, function () {
                            reloadSpuTable();
                        });*/
                    }
                }else {
                    layer.msg("商品下架失败", {
                        icon: 6,
                        time: 1000
                    }, function () {
                        reloadSpuTable();
                    });
                }
            }
        });
    });
}

function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
    if (num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}